package com.liuqi.knet.serialize.hessian2;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.SerializerFactory;
import com.liuqi.knet.serialize.Serialization;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Hessian2
 *
 * @author liuqi
 * @date 2024/12/13 14:44
 **/
public class Hessian2Serialization implements Serialization {

    final SerializerFactory factory = new SerializerFactory(Hessian2Serialization.class.getClassLoader());

    @Override
    public void serialize(OutputStream output, Object obj) throws IOException {
        Hessian2Output h2o = new Hessian2Output(output);
        h2o.setSerializerFactory(factory);
        h2o.writeObject(obj);
        h2o.flushBuffer();
    }

    @Override
    public Object deserialize(InputStream input) throws IOException {
        Hessian2Input h2i = new Hessian2Input(input);
        h2i.setSerializerFactory(factory);
        Object obj = h2i.readObject();
        return obj;
    }

    @Override
    public <T> T deserialize(InputStream input, Class<T> target) throws IOException {
        Hessian2Input h2i = new Hessian2Input(input);
        h2i.setSerializerFactory(factory);
        Object obj = h2i.readObject(target);
        return (T) obj;
    }
}
